// ==UserScript==
// @name           HeroesVsVillains
// @description    autoplayer for the Heroes vs Villains game
// @namespace      facebook
// @version        2.0.6
// @include        http://apps.facebook.com/heroesvillains/*
// @author         blannie
// @contributor	   IEF, colin1497
// ==/UserScript==

var settingsOpen = GM_getValue('settingsOpen', false);
var logOpen = GM_getValue('logOpen', false);
var delay = 10000; //how long to wait between logic loops
var flag = 0; //this flag is used for execution detection.  Setting the flag will prevent further autoplay options from happening during this cycle to ensure the current action completes.
var petvisit = GM_getValue('petvisit', 0); //this will set a petvisit flag every *petvisitfrequency* loads
var petvisitfrequency = 100; //this sets the number of reloads between pet visits, in the future this could be added to the config
var killhealth = 31; // value below which to heal immediately so you don't get killed
var bankgold; //variable to keep gold in bank
var totalgold; //variable to keep total gold in bank and not in bank
var currentTime = new Date();
var lastPlayTime = eval(GM_getValue('lastPlayTime', 0));
var reloadTimer;
var logicTimer;
var winCounter = GM_getValue('winCounter', 0);
var lossCounter= GM_getValue('lossCounter', 0);
var bestProperty = { id:false, roi:0, row:0 };
var nextProperty = GM_getValue('nextProperty', 0);

var SCRIPT = {
	url: 'http://userscripts.org/scripts/source/40919.user.js',
	version: '2.0.6',
	name: 'heroesvillains',
	appID: 'app97498830044',
	money: 'vial',
	clan: 'league',
	presentationurl: 'http://userscripts.org/scripts/show/40919'
};

//---------------  Set up a reload timer in case the logic falls down or we get the FB error page
if (GM_getValue('autoClick', '') == "checked" && GM_getValue('paused')==0)
	{
	reload()
	}
// if we haven't played in more than 2X the max reload frequency, reset petvisit.
if ((currentTime-lastPlayTime)>(GM_getValue('r2', 300))*2000)
	{
 	petvisit=0;
	}
// store currentTime as lastPlayTime if we're not paused
if (GM_getValue('paused')==0)
	{
	GM_setValue('lastPlayTime', uneval(currentTime));
	}


var image = '';

// this needs fixed to deal with hero/villain aspect.	
var missions = new Array(
// Name Hero -- Name Villain, Energy , Tab , Item on tab, form ID, experience(power)
	["Save a cat from a tree -- Mug an innocent bystander",1,1,0,1,1],//1
	["Stop a NYC mugging -- Assassinate a local hero",3,1,1,2,3],	 //2
	["Capture the Mafia Family terrorizing the City -- Unleash a killer virus",5,1,2,3,5], //3
	["Prevent two trains from colliding -- Free the criminals in prison",7,1,3,4,8], //4
	["Foil a casino robbery in Vegas -- Loot treasure from the Pyramids",1,1,4,11,1], //11
	["Protect a UN ambassador -- Plot with your werewolf allies",2,1,5,12,2], //12
	
	["Rescue a damsel in distress -- Plant bombs around the city",10,2,0,5,15], //5
	["Save passengers from a sinking ship -- Blow up a research facility",5,2,1,13,5], //13
	["Imprison a villian in an alternate dimension -- Erase your victims' memories",6,2,2,14,6], //14
	["Prevent the Mad Scientist creating an Army of Robots -- Hold the Mayor hostage",15,2,3,6,20], // 6
	
	
	["Find the Nuke before it detonates -- Assist the Mad Scientist in creating an Army of Robots",18,3,0,7,22], // 7
	["Stop a rogue comet from destroying the Planet Earth -- Sneak into a government facility",25,3,1,8,0], // 8
	["Hone in on a target from far away -- Create a city-wide blackout",13,3,2,16,0], //16
	["Destroy the villaneous Flying Ninjas -- Cause a rogue comet to destroy a city",30,3,3,9,0], // 9  
	["Destroy your archenemy's jungle lair -- Destroy your archenemy's aquatic base",15,3,4,17,0], //17
	
	
	["Save yourself in an Alternate Dimension -- Detonate a Nuke in the city",30,4,0,10,0], // 10
	["Fight global warming -- Create a devastating tornado",35,4,1,19,0], //19
	["Prevent a clone army from dominating the world -- Poison the city's water supply",40,4,2,20,0], //20	
	
	["xxxx","xxxx",255,5,0,15,0], //15
	["xxxx","xxxx",255,5,1,18,0], //18
	["Save the city from cosmic rays","Inundate the city with death rays",50,5,2,21,0], //21
	["Convert a Villain to your side","Convert a Hero to your side",50,5,3,22,0] //22
	);
	
// this needs fixed to deal with hero/villain aspect.
var missionTabs = new Array(
["Lackey (Levels 1-5)"],
["Rookie (Levels 5-8)"],
["Officer (Levels 9-14)"],
["Commander (Levels 15-25)"]
["Mystery Junk (Levels 999999+)"]
);

var curTabMastery = new Array();
var fightUsers = new Array();
var fightDeadmeat= new Array(); //People I can win against
var fightToomuch = new Array(); //People who have beaten me

var XMLHttpFactories = [
    function () {return new XMLHttpRequest()},
    function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

document.getElementsByXPath = function(sValue){ var aResult = new Array();var a = this.evaluate(sValue, ((arguments.lenth > 1) ? arguments[1] : this), null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);for ( var i = 0 ; i < a.snapshotLength ; i++ ){aResult.push(a.snapshotItem(i));}return aResult;};

//Get absolute banner position
bannerTop =   getPositionTop(document.getElementById(SCRIPT.appID+'_banner_row')); //140
bannerLeft =  getPositionLeft(document.getElementById(SCRIPT.appID+'_banner_row')); // 300
var pauseButton = document.createElement("div");

// ---------------------------- Get parsed global variables ------------------//

var alliance =  parseInt(document.body.innerHTML.split('me crew (')[1]);
var gold = document.getElementById(SCRIPT.appID+'_stats_bar_cash').childNodes[1].childNodes[2].innerHTML.substring(document.getElementById(SCRIPT.appID+'_stats_bar_cash').childNodes[1].childNodes[2].innerHTML.indexOf(">")+1);
	gold = parseInt(gold.replace(/,/g, ''));
var health = parseInt(document.getElementById(SCRIPT.appID+'_current_health').innerHTML);
var maxenergy = document.getElementById(SCRIPT.appID+'_current_energy').parentNode.innerHTML.substring(document.getElementById(SCRIPT.appID+'_current_energy').parentNode.innerHTML.indexOf(">/")+2);
var maxStamina = document.getElementById(SCRIPT.appID+'_current_stamina').parentNode.innerHTML.substring(document.getElementById(SCRIPT.appID+'_current_stamina').parentNode.innerHTML.indexOf(">/")+2);
var energy = parseInt(document.getElementById( SCRIPT.appID+'_current_energy').innerHTML);
var stamina = parseInt(document.getElementById( SCRIPT.appID+'_current_stamina').innerHTML);
var experience = document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.substring(0,document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.indexOf("/"));
var nextlevelexperience = document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.substring(document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.indexOf("/")+1);
var experiencetolevel= nextlevelexperience - experience;

// ---------------------------- menu global variables ------------------------------------//

var settingsButton
var viewLogButton
var clrLogButton
var settingsBox
var logBox
var versionBox
var autoClick
var refreshTimes
var autoProperty
var autoMission
var missionMastery 
var selectMission
var choiceTab
var choice
var autoBank
var bankConfig
var bankKeep
var autoHeal
var healthLevel
var healthRage
var updateButton
var autoFight
var fightMinimum
var fightRandom
var fightLevel
var fightClanSize
var freshMeat
var fightList
var autoTreasure
var autoPet
var autoStats
var statAtt
var statDef
var statEnergy
var statHP
var statStrength
var autoIsland
var saveButton
var saveNotification
var buyCrewProperty
   


//Grab the last known request form ID
var reqID = GM_getValue('reqformID',false);

//If we don't have a reqID or its older than a day, grab a fresh one.
if (!reqID)
{
	if (location.href.indexOf(SCRIPT.name+'/recruit') != -1)
	{
		Array.forEach(document.getElementsByTagName("input"),
			function(obj)
			{
				if (obj.id.indexOf('mfs_typeahead_req_form_') != -1)
				{
					GM_setValue('reqformID',obj.id.replace('mfs_typeahead_req_form_',''));
					return;
				}
			}
		);
	}
	else
		window.location = "http://apps.facebook.com/"+SCRIPT.name+"/recruit.php";
	return;
}

/*
var members = document.getElementsByXPath("//a[contains(@href,'/"+SCRIPT.name+"/stats.php?user=')]");
//First link is always yourself from the 'my stats' link at the top
 Array.forEach(members,
	 function(member){
		var mobid = member.href.match(/\d+$/);
		var newImg = document.createElement("img");
		newImg.setAttribute("src", image);
		newImg.addEventListener('click',invitePlayer(mobid), false);
		member.parentNode.insertBefore(newImg,member);
	 }
	 );
*/
	 




//***********************************************************
//-------------Logic here runs every page reload--------------
//***********************************************************

// --------------  Call the pause/unpause setup function ----------------//
pause()
// --------------  Build the configuration and log windows --------//
buildmenus()
// --------------  Parse whatever window we're on and log ---------//
parseandlog()
// --------------  Scan the fight list any time we happen to be on the fight page
if (GM_getValue('fightUsers', '') != '')
	{
	fightUsers=eval(GM_getValue('fightUsers', ''));
	}
if (location.href.indexOf(SCRIPT.name+'/fight') != -1)
	{
	scanfightlist()
	}
// --------------  If we're on the properties page, put data on the screen
if (location.href.indexOf(SCRIPT.name+'/properties') != -1)
	{
	propertydata()
	}
//---------------  Decrement petvisit every load
petvisit = petvisit - 1
if (petvisit < 0)
	{
	petvisit = 0;
	}
//---------------  Store pet visit value for next page load
GM_setValue('petvisit', petvisit);
//---------------  Check if paused, if not, run autoplay logic loop
if (GM_getValue('paused')==0)
	{
//	while (flag == 0)
//		{
			logicTimer=window.setTimeout(logic, 3000);
//		}
	}
